package com.wisewill.wakeonlan.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

import android.os.Environment;

public class PropertyUtil{
	private static final File confFile = new File(new File(Environment.getExternalStorageDirectory(), "WOL"), "conf.properties");
	static Properties prop = readProp();
	private static Properties readProp(){
		if(!confFile.exists())
			try {
				if(confFile.getParentFile().isDirectory())
					confFile.createNewFile();
				else{
					confFile.getParentFile().mkdirs();
					confFile.createNewFile();
				}
			} catch (IOException e1) {
				throw new RuntimeException(e1);
			}
		
		InputStream is = null;
		Properties ret = new Properties();
		try {
			is = new FileInputStream(confFile);
			ret.load(is);
			return ret;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			if(is != null)
				IOUtils.closeQuietly(is);
		}
	}
	
	public static String getProp(String key){
		return prop.getProperty(key);
	}
	
	public synchronized static void setProp(String key, String value){
		prop.setProperty(key, value);
		try{
			OutputStream os = new FileOutputStream(confFile);
			try{
				prop.store(os, null);
			}finally{
				os.close();
			}
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
		prop = readProp();
	}
	
	public static void main(String[] args) {
		System.err.println(getProp("conf.emailreaper.pop3.host"));
		setProp("fff", "123");
		System.err.println(getProp("fff"));
	}
}
